package com.example.werthwedemo0309;

import com.example.werthwedemo0309.IntentData.BaseApplication;
import com.example.werthwedemo0309.IntentData.CityResponse;
import com.example.werthwedemo0309.IntentData.IWeatherLogic;
import com.example.werthwedemo0309.IntentData.IWeatherPresenter;
import com.example.werthwedemo0309.IntentData.WeatherListResponse;

import java.util.ArrayList;
import java.util.List;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class WeatherPresenter implements IWeatherLogic
{

    @Override
    public void requestCityList(String key, IWeatherPresenter callback)
    {
        List<CityModel> cityModels = new ArrayList<>();

        BaseApplication.httpbinService.requestCityList(key)
                .flatMap(new Func1<WeatherListResponse<CityResponse>, Observable<CityResponse>>()
                {
                    @Override
                    public Observable<CityResponse> call(
                            WeatherListResponse<CityResponse> cityResponseWeatherListResponse)
                    {
                        return Observable.from(cityResponseWeatherListResponse.getResult());
                    }
                })
                .map(cityResponse ->
                {
                    CityModel model = new CityModel();
                    model.setId(cityResponse.getId());
                    model.setCity(cityResponse.getCity());

                    return model;
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<CityModel>()
                {
                    @Override
                    public void onCompleted()
                    {
                        callback.onCityListSuccess(cityModels);
                    }
                    @Override
                    public void onError(Throwable e)
                    {
                        e.printStackTrace();
                    }
                    @Override
                    public void onNext(CityModel cityModel)
                    {
                        cityModels.add(cityModel);
                    }
                });
    }
}

